from datetime import datetime, timedelta

from playhouse.shortcuts import model_to_dict

from bitget.bitget_ticker_n_model import create_bitget_ticker_n_model
from bitget.bitget_ticker_o_model import BitgetTickerO
from config.base_config import *


def auto_download_ticker():
    '''
    自动更新深度数据
    :return:
    '''
    # 获取第一条数据的时间和当前时间，取整算出n值
    ticker_o = BitgetTickerO.select().first()
    begin_time = ticker_o.create_time
    begin = datetime.strftime(begin_time, "%Y-%m-%d %H:%M:%S")
    # 当前时间
    current_date = datetime.now()
    # 计算天数差
    days_difference = (current_date - begin_time).days
    bitget_download_ticker_cycle(days_difference, begin)


def bitget_download_ticker_cycle(n, begin):
    for i in range(n):
        logging.info(f"第{i}次获取数据，时间为：{begin}")
        bitget_download_ticker(begin)
        begin_time = datetime.strptime(begin, "%Y-%m-%d %H:%M:%S")
        end_time = begin_time + timedelta(days=1)
        begin = end_time.strftime('%Y-%m-%d %H:%M:%S')
        logging.info(f"结束")


def bitget_download_ticker(begin):
    '''
    1,查询原库（database_o库）数据（100条）
    2,插入到mycat库（database_cat）
    3,从原库删除这100条数据
    :return:
    '''
    i = 0
    bitget_ticker_btc_name = "bitget_ticker_btcusdtswap_" + (datetime.strptime(begin, "%Y-%m-%d %H:%M:%S")).strftime(
        '%Y-%m-%d')
    bitget_ticker_eth_name = "bitget_ticker_ethusdtswap_" + (datetime.strptime(begin, "%Y-%m-%d %H:%M:%S")).strftime(
        '%Y-%m-%d')
    BitgetTickerBtc = create_bitget_ticker_n_model(bitget_ticker_btc_name)
    BitgetTickerEth = create_bitget_ticker_n_model(bitget_ticker_eth_name)
    while True:
        i = i + 1
        logging.info(f"循环第{i}次")
        list_o = BitgetTickerO.select().limit(1000)
        bitget_ticker_o_ids_to_delete = []
        bitget_ticker_btc_list = []
        bitget_ticker_eth_list = []
        # 将字符串转换为datetime对象
        begin_time = datetime.strptime(begin, "%Y-%m-%d %H:%M:%S").replace(hour=0, minute=0, second=0)
        end_time = begin_time + timedelta(days=1)
        flag = False
        # 执行查询并打印结果
        for bitget_ticker_o in list_o:
            # 时间判断，之前的全部删除
            if bitget_ticker_o.create_time < begin_time:
                bitget_ticker_o_ids_to_delete.append(bitget_ticker_o.id)
            elif bitget_ticker_o.create_time >= end_time:
                logging.info("超过了")
                flag = True
                break
            else:
                bitget_ticker_o_ids_to_delete.append(bitget_ticker_o.id)
                bitget_ticker_o_dict = model_to_dict(bitget_ticker_o)
                if bitget_ticker_o.inst_id == "BTCUSDT":
                    bitget_ticker_btc = BitgetTickerBtc(**bitget_ticker_o_dict)
                    bitget_ticker_btc.id = None
                    bitget_ticker_btc_list.append(bitget_ticker_btc)
                else:
                    bitget_ticker_eth = BitgetTickerEth(**bitget_ticker_o_dict)
                    bitget_ticker_eth.id = None
                    bitget_ticker_eth_list.append(bitget_ticker_eth)
        if len(bitget_ticker_btc_list) > 0:
            BitgetTickerBtc.bulk_create(bitget_ticker_btc_list)
        if len(bitget_ticker_eth_list) > 0:
            BitgetTickerEth.bulk_create(bitget_ticker_eth_list)
        # 批量删除这些记录
        if len(bitget_ticker_o_ids_to_delete) > 0:
            BitgetTickerO.delete().where(BitgetTickerO.id.in_(bitget_ticker_o_ids_to_delete)).execute()
        if flag:
            logging.info("存储完成")
            break
    db_o = get_db_o()
    db_n = get_db_n()
    if not db_n.is_closed():
        db_n.close()
    if not db_o.is_closed():
        db_o.close()
